package com.firewolf.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 作者：刘兴
 * 时间:18/11/26
 **/
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/hello").permitAll() //指定某系请求直接放过
                .antMatchers("/").permitAll()
                .antMatchers("/index.jsp").permitAll()
                .antMatchers("/**").hasRole("USER")//指定某些请求必须有什么角色
                .anyRequest().authenticated() //指定认证情况，这里所有的页面都需要认证
                .and()
                .formLogin()
                .loginPage("/login")  //自定义返回的登录页面，指定登录页面为login请求返回的页面
                .permitAll();//登录页面必须让所有用户都能访问，否则就没法登录了

        //配置登出使用的路径已经退出成功的页面
        http
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/");//退出失败跳转到主页
//                .logoutSuccessHandler(logoutSuccessHandler)
//                .invalidateHttpSession(true)
//                .addLogoutHandler(logoutHandler)
//                .deleteCookies(cookieNamesToClear);
    }

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder().username("1").password("1").roles("USER").build());
        return manager;
    }
}
